package de.revdev.llt.module.learning;

import de.revdev.llt.module.utility.AbstractFacade;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

/**
 *
 * @author f.lindermaier
 */
@Stateless
public class LearnStatusFCFacade extends AbstractFacade<LearnStatusFC> {

    @PersistenceContext(unitName = "LetsLearnTogetherPU")
    private EntityManager em;

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    public LearnStatusFCFacade() {
        super(LearnStatusFC.class);
    }

    public Long countStatusFromFCB(LearnStatusFC.Status status, LearnStatusFCB learnStatusFCB) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Long> cq = cb.createQuery(Long.class);
            Root<LearnStatusFC> r = cq.from(LearnStatusFC.class);
            cq.select(cb.count(r));
            ParameterExpression<LearnStatusFC.Status> p = cb.parameter(LearnStatusFC.Status.class);
            ParameterExpression<LearnStatusFCB> q = cb.parameter(LearnStatusFCB.class);
            cq.where(cb.equal(r.get(LearnStatusFC_.learnCategory), p), cb.equal(r.get(LearnStatusFC_.learnStatusFCB), q));
            return (Long) em.createQuery(cq).setParameter(p, status).setParameter(q, learnStatusFCB).getSingleResult();
        } catch (Exception e) {
            return new Long(0);
        }
    }

    public List<LearnStatusFC> getLearnStatusFCForLSFCBAndStatus(LearnStatusFCB learnStatusFCB, LearnStatusFC.Status status) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<LearnStatusFC> cq = cb.createQuery(LearnStatusFC.class);
            Root<LearnStatusFC> r = cq.from(LearnStatusFC.class);
            cq.select(r);
            ParameterExpression<LearnStatusFCB> p = cb.parameter(LearnStatusFCB.class);
            ParameterExpression<LearnStatusFC.Status> q = cb.parameter(LearnStatusFC.Status.class);
            cq.where(cb.equal(r.get(LearnStatusFC_.learnCategory), q), cb.equal(r.get(LearnStatusFC_.learnStatusFCB), p));
            cq.orderBy(cb.desc(r.get(LearnStatusFC_.lastDateAnswered)));
            return em.createQuery(cq).setParameter(p, learnStatusFCB).setParameter(q, status).getResultList();
        } catch (Exception e) {
            return new LinkedList<>();
        }
    }
}